import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base/common/commonColors.dart';
import 'package:flutter_base/common/fun.dart';
import 'package:flutter_base/widgets/refreshListView.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

/// Create： Zhang 3/19/21 5:49 PM
/// 描述：所有弹窗在这里管理

class AlertDialogAction {
  String action;
  Color color;

  AlertDialogAction({this.action = "知道了", this.color = Colors.blue});
}

///弹出成功的弹框提示
void toastSuc(String msg) async {
  await EasyLoading.showSuccess(msg);
}

///错误弹框
void toastError(String msg) async {
  await EasyLoading.showError(msg);
}

///loading框
void toastLoading({String? msg}) async {
  await EasyLoading.show(
    status: msg ?? "正在加载...",
    indicator: Container(
      width: 40,
      height: 40,
      alignment: Alignment.center,
      child: loadingView(color: Colors.white),
    ),
    maskType: EasyLoadingMaskType.clear,
  );
}

///info弹框
void toastInfo(String msg) async {
  await EasyLoading.showInfo(msg);
}

///toast弹框
void toast(String msg) async {
  await EasyLoading.showToast(
    msg.isEmpty ? "空消息提示" : msg,
    toastPosition: EasyLoadingToastPosition.bottom,
  );
}

///进度提示框
void toastProgress(double progress, {String? msg}) async {
  await EasyLoading.showProgress(
    progress,
    status: msg ?? "正在加载...",
    maskType: EasyLoadingMaskType.clear,
  );
}

///消失弹框
void dismissLoading() async {
  await EasyLoading.dismiss();
}

///对话框初始化
TransitionBuilder initDialog() => EasyLoading.init();

///alert对话框
void showAlert(
  BuildContext context, {
  String title: "提示",
  required String msg,
  //定义底部的按钮
  required List<AlertDialogAction> actions,
  //方法回调
  Callback<String>? callback,
}) async {
  await showCupertinoDialog(
    context: context,
    barrierDismissible: true,
    builder: (context) {
      return CupertinoAlertDialog(
        title: Text(title),
        content: Text(msg, style: TextStyle(fontSize: 16)),
        actions: actions
            .map(
              (action) => TextButton(
                child: Text(
                  action.action,
                  style: TextStyle(color: action.color, fontSize: 16),
                ),
                onPressed: () {
                  if (callback != null) {
                    callback(action.action);
                  } else {
                    Navigator.of(context).pop();
                  }
                }, // 关闭对话框
              ),
            )
            .toList(),
      );
    },
  );
}

///底部弹出的自定义内容对话框
void showBottomWidget(
  BuildContext context, {
  required Widget content,
  bool isDismissible = true,
  bool enableDrag = true,
}) async {
  await showModalBottomSheet(
    context: context,
    isDismissible: isDismissible,
    enableDrag: enableDrag,
    backgroundColor: Colors.white,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.only(
        topLeft: Radius.circular(20),
        topRight: Radius.circular(20),
      ),
    ),
    builder: (context) {
      return content;
    },
  );
}

///底部弹出的选择对话框
void showBottomMenu(
  BuildContext context, {
  required List<String?> items,
  required SellectCallback callback,
  isDismissible = true,
}) async {
  await showModalBottomSheet(
    context: context,
    isDismissible: isDismissible,
    backgroundColor: Colors.white,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.only(
        topLeft: Radius.circular(20),
        topRight: Radius.circular(20),
      ),
    ),
    builder: (context) {
      return SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Column(
          children: items
              .map(
                (item) => Column(
                  children: [
                    InkWell(
                      splashColor: Colors.transparent,
                      child: Container(
                        width: double.infinity,
                        height: 55,
                        alignment: Alignment.center,
                        child: Text(
                          item!,
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.black87,
                          ),
                        ),
                      ),
                      onTap: () {
                        Navigator.of(context).pop();
                        callback(items.indexOf(item), item);
                      },
                    ),
                    Container(
                      width: double.infinity,
                      height: 1,
                      margin: EdgeInsets.only(left: 20, right: 20),
                      color: defaultBgColor,
                    ),
                  ],
                ),
              )
              .toList(),
        ),
      );
    },
  );
}

///底部弹出的对话框,可多选  ##控件定义由此开始##
void showBottomCheck(
  BuildContext context, {
  required List<CheckItem> items,
  required Callback<Set<int>> callback,
}) async {
  await showModalBottomSheet(
    context: context,
    backgroundColor: Colors.white,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.only(
        topLeft: Radius.circular(20),
        topRight: Radius.circular(20),
      ),
    ),
    builder: (context) {
      return CheckList(items, callback);
    },
  );
}

class CheckItem {
  final String itemTitle;
  bool isChecked = false;

  CheckItem(this.itemTitle, {isChecked});
}

class CheckList extends StatefulWidget {
  final List<CheckItem> _items;
  final Callback<Set<int>> _callback;

  CheckList(this._items, this._callback);

  @override
  State<StatefulWidget> createState() => CheckListState();
}

class CheckListState extends State<CheckList> {
  final Set<int> checkedIndex = {};

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: SingleChildScrollView(
            physics: BouncingScrollPhysics(),
            child: Column(
              children: [
                Column(
                  children: widget._items.map((item) {
                    return Column(
                      children: [
                        CheckboxListTile(
                          title: Padding(
                            padding: EdgeInsets.only(left: 15),
                            child: Text(
                              item.itemTitle,
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.black87,
                              ),
                            ),
                          ),
                          checkColor: Colors.blue,
                          value: item.isChecked,
                          onChanged: (check) {
                            if (check!) {
                              checkedIndex.add(widget._items.indexOf(item));
                            } else {
                              checkedIndex.remove(widget._items.indexOf(item));
                            }
                            setState(() {
                              item.isChecked = check;
                            });
                          },
                        ),
                        Container(
                          width: double.infinity,
                          height: 1,
                          margin: EdgeInsets.only(left: 20, right: 20),
                          color: defaultBgColor,
                        ),
                      ],
                    );
                  }).toList(),
                ),
              ],
            ),
          ),
        ),
        Row(
          children: [
            Expanded(
              child: Container(
                color: defaultBgColor,
                child: TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text(
                    "取消",
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey,
                    ),
                  ),
                ),
              ),
            ),
            Expanded(
              child: Container(
                color: Colors.blue,
                child: TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    widget._callback(checkedIndex);
                  },
                  child: Text(
                    "确定",
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }
}

///底部弹出的对话框,可多选  ##控件定义由此结束##

///日期选择
void showDateTimePicker(
  BuildContext context, {
  required Callback<DateTime> onConfirm,
  dateFormat = 'yyyy年-MM月-dd日 H点:m分:s秒',
}) {
  DatePicker.showDatePicker(
    context,
    initialDateTime: DateTime.now(),
    dateFormat: dateFormat,
    locale: DateTimePickerLocale.zh_cn,
    pickerTheme: DateTimePickerTheme(
      showTitle: true,
      pickerHeight: 270,
      itemHeight: 42,
      itemTextStyle: TextStyle(fontSize: 15),
      confirmTextStyle: TextStyle(
          color: Colors.green, fontSize: 15, fontWeight: FontWeight.bold),
      cancelTextStyle: TextStyle(
          color: Colors.black54, fontSize: 15, fontWeight: FontWeight.bold),
    ),
    pickerMode: DateTimePickerMode.datetime,
    onConfirm: (dateTime, List<int> index) => onConfirm(dateTime),
  );
}
